<template>
  <div class="Infos">
    <div class="top">
      <el-upload
        class="top-img"
        :show-file-list="false"
        :http-request="handleRequest"
      >
        <img :src="infosData.avater" class="img" />
      </el-upload>
    </div>
    <div class="bottom">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="个人信息" name="first">
          <el-form
            label-width="100px"
            :model="infosData"
            style="max-width: 460px"
          >
            <el-form-item label="姓名">
              <el-input v-model="infosData.userName" />
            </el-form-item>
            <el-form-item label="性别">
              <el-input v-model="infosData.userSex" />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="infosData.phone" />
            </el-form-item>
            <el-form-item label="地址">
              <el-input v-model="infosData.address" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateInfos"
                >保存修改</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="修改密码" name="second">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            class="demo-ruleForm"
          >
            <el-form-item label="原密码：" prop="initPass">
              <el-input v-model="ruleForm.initPass" type="password" />
            </el-form-item>
            <el-form-item label="新密码：" prop="updatePass">
              <el-input v-model="ruleForm.updatePass" type="password" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)"
                >确认修改</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox, type FormInstance } from "element-plus";
import { ref, onMounted, getCurrentInstance, reactive } from "vue";
import { useLogin } from "@/hooks/loginForm/useLogin";

const activeName = ref("first");
const { proxy }: any = getCurrentInstance();
const infosData = ref<any>({});
const saveUrl = ref("");

const { bcrypt } = useLogin();
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  initPass: "",
  updatePass: "",
});

onMounted(async () => {
  await getInfos();
});

function getInfos() {
  infosData.value = JSON.parse(
    window.sessionStorage.getItem("adminInfos") || "null"
  );
}

const updateInfos = () => {
  proxy.$http
    .post("/user/upinfos/" + infosData.value.id, {
      userName: infosData.value.userName,
      userSex: infosData.value.userSex,
      phone: infosData.value.phone,
      address: infosData.value.address,
    })
    .then(async (res: any) => {
      ElMessageBox.alert("你的信息保存成功", {
        confirmButtonText: "OK",
        callback: () => {
          ElMessage({
            type: "success",
            message: "提交成功",
          });
        },
      });
      window.sessionStorage.setItem("adminInfos", JSON.stringify(res.data));
      await getInfos();
    });
};
const handleRequest = (e: any) => {
  const fd = new FileReader();
  fd.readAsDataURL(e.file);
  saveUrl.value = "https://img2.baidu.com/it/" + e.file.name.slice(0, -5);
  proxy.$http
    .post("/user/upinfos/" + infosData.value.id, {
      avater: saveUrl.value,
    })
    .then(async (res: any) => {
      ElMessage.success(res.message);
      window.sessionStorage.setItem("adminInfos", JSON.stringify(res.data));
      await getInfos();
      location.reload()
    });
};

const validateInitPass = (rule: any, value: any, callback: any) => {
  const flag = bcrypt.compareSync(ruleForm.initPass, infosData.value.userPass);
  if (value === "") {
    callback(new Error("请输入原密码"));
  } else if (!flag) {
    callback(new Error("原密码错误"));
  } else {
    callback();
  }
};
const validateUpdatePass = (rule: any, value: any, callback: any) => {
  const flags = bcrypt.compareSync(
    ruleForm.updatePass,
    infosData.value.userPass
  );
  if (value === "") {
    callback(new Error("新密码不能为空"));
  } else if (flags) {
    callback(new Error("新密码与原密码相同"));
  } else {
    callback();
  }
};

const rules = reactive({
  initPass: [{ validator: validateInitPass, trigger: "blur" }],
  updatePass: [{ validator: validateUpdatePass, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      proxy.$http
        .post("/user/upPass/" + infosData.value.id, {
          userPass: ruleForm.updatePass,
        })
        .then(async (res: any) => {
          ElMessage.success(res.message);
          ruleForm.initPass = "";
          ruleForm.updatePass = "";
          window.sessionStorage.setItem("adminInfos", JSON.stringify(res.data));
          await getInfos();
        });
    } else {
      return false;
    }
  });
};
</script>

<style lang="less" scoped>
.Infos {
  margin: 50px auto;
  width: 50%;
  background-color: #eee;
  border-radius: 10px;
  box-shadow: 0 0 5px 5px rgb(224, 220, 220);
  display: flex;
  flex-direction: column;
  padding: 10px 20px;
  .top {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    &-img {
      margin: 30px;
      width: 150px;
      .img {
        width: 100%;
        height: 100%;
        border-radius: 10%;
      }
    }
    .name {
      font-size: 24px;
      font-weight: 600;
    }
  }
}
</style>
